import React, { useEffect, useMemo, useState, useRef, useCallback } from 'react';
import { Form, Tooltip } from 'antd';
import { Data, FormControlProps } from '../types';
import { usePrevious } from '../../../utils/hooks';
import { unitConversion } from '../../../utils';
import css from '../styles.less';

interface FormItemProps {
  data: Data;
  com: any;
  item: any;
  // field: any;
  slots: any;
  isMobile: boolean;
}

const JSXWrapper = (props: FormControlProps) => {
  const { com, value, onChange, field } = props;

  // useLayoutEffect(() => { // 初始化表单项值
  //   com.inputs?.setValue(value) // 需求区分 表单API行为触发 与 用户行为触发 => inputs or _inputs
  // }, [value])

  return com.jsx;
};

const FormItem = (props) => {
  const { com, item, data, slots, isMobile, env } = props;
  const { dynamicStyle = {}, label } = item;
  const [isShowTips, setIsShowTips] = useState(false);
  const formColon = data.config?.colon || data.colon;
  const colon = item?.colon === 'default' ? formColon : item.colon;
  const labelRef = useRef<HTMLLabelElement>();
  const prevLabel = usePrevious(label);

  const labelAlign =
    dynamicStyle.labelAlign && dynamicStyle.labelAlign !== 'default'
      ? dynamicStyle?.labelAlign
      : void 0;
  const labelCol =
    item?.labelWidthType === 'default'
      ? void 0
      : { flex: `0 0 ${item.labelWidth ? item.labelWidth : 98}px` };

  const whiteSpace =
    dynamicStyle.labelAutoWrap && dynamicStyle.labelAutoWrap !== 'default'
      ? dynamicStyle.labelAutoWrap
        ? 'pre-wrap'
        : 'nowrap'
      : void 0;
  const ellipseConfig = useMemo(() => {
    if (data.ellipseMode === 'ellipse') {
      return {
        overflow: 'hidden',
        WebkitBoxOrient: 'vertical',
        wordBreak: 'break-all',
        textOverflow: 'ellipsis',
        display: '-webkit-box !important'
      };
    }
    if ((data.ellipseMode = 'wrap')) {
      return {
        whiteSpace: 'pre-wrap'
      };
    }
    return {};
  }, [data.ellipseMode]);
  useEffect(() => {
    if (env.runtime && data.ellipseMode === 'ellipse' && labelRef.current) {
      const labelRefWidth = labelRef.current?.offsetWidth;
      if (labelRef.current.scrollWidth > labelRefWidth) {
        setIsShowTips(true);
      } else {
        setIsShowTips(false);
      }
    }
  }, [labelRef.current, env.runtime, data.ellipseMode, item.label, dynamicStyle.labelAutoWrap]);

  const handleMouseEnter = useCallback(() => {
    if (
      data.layoutType === 'Form' ||
      env.edit ||
      dynamicStyle.labelAutoWrap === true ||
      data.ellipseMode === 'wrap'
    ) {
      // 基础表单、编辑态、自动换行不做处理
      return;
    }
    if (isShowTips && prevLabel === item.label) {
      return;
    }
    try {
      const labelRefWidth = labelRef.current?.offsetWidth;
      if (labelRef.current.scrollWidth > labelRefWidth) {
        setIsShowTips(true);
      } else {
        setIsShowTips(false);
      }
    } catch (error) {
      setIsShowTips(false);
    }
  }, [data.layoutType, item.label, prevLabel, isShowTips]);

  return (
    <Form.Item
      label={
        item?.hiddenLabel || (isMobile && item?.label?.trim()?.length === 0) ? (
          void 0
        ) : item.labelSlot ? (
          slots[item.labelSlot]?.render({ scope: com.scope })
        ) : (
          <label
            ref={labelRef}
            data-form-item={com.name}
            onMouseEnter={handleMouseEnter}
            style={{ ...dynamicStyle.labelStyle, whiteSpace, ...ellipseConfig }}
          >
            <Tooltip
              placement="topLeft"
              title={isShowTips && env.runtime ? env.i18n(item?.label) : null}
            >
              {env.i18n(item?.label)}
            </Tooltip>
          </label>
        )
      }
      className={item.labelSlot ? css.customLabel : void 0}
      labelCol={labelCol}
      labelAlign={labelAlign}
      name={item?.name}
      required={item?.required}
      validateStatus={item?.validateStatus}
      help={item?.help}
      tooltip={env.i18n(item?.tooltip)}
      colon={!!item?.label && colon}
      hidden={item?.hidden}
    >
      <div className={css.formItemControl}>
        <div className={css.formItemSlotContent}>
          <JSXWrapper com={com} />
        </div>
        {item.slotAfter && (
          <div className={css.formItemSlotAfter}>
            {<Form.Item noStyle>{slots[item.slotAfter]?.render({ scope: com.scope })}</Form.Item>}
          </div>
        )}
      </div>

      {item.description && (
        <div className={`${css.formItemDesc}`}>
          <Form.Item noStyle>
            <span className="formItemDesc" style={dynamicStyle.descriptionStyle}>
              {env.i18n(item.description)}
            </span>
          </Form.Item>
        </div>
      )}
    </Form.Item>
  );
};

export default FormItem;
